package classes
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.getQualifiedClassName;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;
	
	[Bindable]
	public class TagHandler extends EventDispatcher
	{
		private static var instance:TagHandler = null;
		private var _tagList:ArrayCollection;
		
		[Bindable("tagListChanged")]
		public function get tagList():ArrayCollection{
			return _tagList;
		}
		
		public function TagHandler(){
			super();
		}
		
		public function addTags(fileName:String, tags:String):void{
			dispatchEvent(new Event("tagging"));
			var taggingService:HTTPService = new HTTPService();
			taggingService.url = Settings.getInstance().taggingServletURL;
			taggingService.method = "POST";
			taggingService.addEventListener(ResultEvent.RESULT, taggingServiceResultHandler);
			taggingService.send({filename:fileName, tag:tags});
		}
		
		public function updateTags():void{
			dispatchEvent(new Event("updatingTags"));
			var getTagsService:HTTPService = new HTTPService();
			getTagsService.url = Settings.getInstance().getTagsServletURL;
			getTagsService.method = "GET";
			getTagsService.addEventListener(ResultEvent.RESULT, getTagsServiceResultHandler);
			getTagsService.send();
		}
		
		
		private function getTagsServiceResultHandler(event:ResultEvent):void{
			_tagList = new ArrayCollection();
			if(event.result.toString() == "FAIL"){
				dispatchEvent(new Event("tagError"));
				return;
			}
			if(event.result.tags == null) return;
			if(getQualifiedClassName(event.result.tags.tag)=="mx.utils::ObjectProxy"){
				_tagList.addItem(event.result.tags.tag.name.toString());
			}else for each(var item:Object in event.result.tags.tag){
				_tagList.addItem(item.name.toString());
			}
			dispatchEvent(new Event("tagListChanged"));
		}
		
		private function taggingServiceResultHandler(event:ResultEvent):void{
			if(event.result.toString()=="OK"){
				dispatchEvent(new Event("tagOK"));
				this.updateTags();
			}
		}
		
		public static function getInstance():TagHandler{
			if(instance==null){
				instance = new TagHandler();
			}
			return instance;
		}
	}
}